/* global marked */
/* eslint-disable no-unused-vars */
console.log('Content script loaded!');

// 配置 marked
marked.setOptions({
    gfm: true,
    breaks: true,
    headerIds: false,
    mangle: false
});

// 创建侧边栏
function createSidebar() {
    console.log('Creating sidebar...');
    const sidebar = document.createElement('div');
    sidebar.id = 'dataflux-ai-sidebar';
    
    // 创建侧边栏内容
    sidebar.innerHTML = `
        <div class="dataflux-sidebar-resize"></div>
        <div class="dataflux-sidebar-header">
            <h2 class="dataflux-sidebar-title">DataFlux AI 助手</h2>
            <button class="dataflux-close-btn" id="dataflux-close-btn">
                <svg viewBox="0 0 24 24">
                    <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" fill="currentColor"/>
                </svg>
            </button>
        </div>
        <div class="dataflux-sidebar-wrapper">
            <div class="dataflux-sidebar-content">
                <!-- 对话内容将在这里动态插入 -->
            </div>
            <div class="dataflux-sidebar-footer">
                <div class="dataflux-action-buttons">
                    <button class="dataflux-action-btn summary" id="summary-btn">
                        <svg viewBox="0 0 24 24">
                            <path d="M14,17H7V15H14M17,13H7V11H17M17,9H7V7H17M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z" fill="currentColor"/>
                        </svg>
                        总结全文
                    </button>
                    <button class="dataflux-action-btn mindmap" id="mindmap-btn">
                        <svg viewBox="0 0 24 24">
                            <path d="M17,15.5H12V17.5H17V15.5M16,8.5H12V10.5H16V8.5M16.4,2H7.6C6.7,2 6,2.7 6,3.6V20.4C6,21.3 6.7,22 7.6,22H16.4C17.3,22 18,21.3 18,20.4V3.6C18,2.7 17.3,2 16.4,2M16,20H8V4H16V20M9,11.5H11V13.5H9V11.5M9,15.5H11V17.5H9V15.5M9,8.5H11V10.5H9V8.5Z" fill="currentColor"/>
                        </svg>
                        思维导图
                    </button>
                </div>
                <div class="dataflux-model-select-container">
                    <label for="sidebar-model-select">选择AI模型：</label>
                    <select id="sidebar-model-select" class="sidebar-model-select">
                        <option value="deepseek">DeepSeek</option>
                        <option value="ali" selected>阿里通义</option>
                    </select>
                </div>
                <div class="dataflux-input-group">
                    <textarea 
                        class="dataflux-input"
                        id="dataflux-input"
                        placeholder="输入您的问题..."
                        rows="1"
                    ></textarea>
                    <button class="dataflux-send-btn" id="dataflux-send-btn" disabled>
                        <svg viewBox="0 0 24 24">
                            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" fill="currentColor"/>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(sidebar);
    console.log('Sidebar created and appended to body');
    
    // 添加事件监听器
    setupEventListeners(sidebar);
    
    return sidebar;
}

// 设置事件监听器
function setupEventListeners(sidebar) {
    // 关闭按钮
    const closeBtn = sidebar.querySelector('#dataflux-close-btn');
    closeBtn.addEventListener('click', () => {
        console.log('Close button clicked');
        closeSidebar(sidebar);
    });
    
    // 功能按钮
    const summaryBtn = sidebar.querySelector('#summary-btn');
    const mindmapBtn = sidebar.querySelector('#mindmap-btn');
    
    summaryBtn.addEventListener('click', () => {
        console.log('Summary button clicked');
        handleSummary();
    });
    
    mindmapBtn.addEventListener('click', () => {
        console.log('Mindmap button clicked');
        handleMindmap();
    });
    
    // 输入框和发送按钮
    const input = sidebar.querySelector('#dataflux-input');
    const sendBtn = sidebar.querySelector('#dataflux-send-btn');
    
    input.addEventListener('input', () => {
        sendBtn.disabled = !input.value.trim();
    });
    
    // 移除回车发送功能，改为只允许换行
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            input.value += '\n';
        }
    });
    
    sendBtn.addEventListener('click', () => {
        if (input.value.trim()) {
            handleSendMessage(input.value);
            input.value = '';
            sendBtn.disabled = true;
        }
    });
    
    // 侧边栏拖动调整宽度
    const resizeHandle = sidebar.querySelector('.dataflux-sidebar-resize');
    let isResizing = false;
    let startX;
    let startWidth;
    let overlay;
    
    resizeHandle.addEventListener('mousedown', (e) => {
        isResizing = true;
        startX = e.pageX;
        startWidth = parseInt(getComputedStyle(sidebar).width, 10);
        
        // 创建遮罩层
        overlay = document.createElement('div');
        overlay.className = 'resize-overlay';
        document.body.appendChild(overlay);
        
        // 添加拖动时的视觉反馈
        document.body.style.cursor = 'ew-resize';
        resizeHandle.style.opacity = '1';
    });
    
    document.addEventListener('mousemove', (e) => {
        if (!isResizing) return;
        
        // 计算新宽度（注意是向左拖动，所以是加上差值）
        const width = startWidth - (e.pageX - startX);
        
        // 限制最小和最大宽度
        if (width >= 300 && width <= 800) {
            sidebar.style.width = `${width}px`;
            
            // 更新内容区域的宽度
            const contentArea = sidebar.querySelector('.dataflux-sidebar-content');
            if (contentArea) {
                contentArea.style.width = `${width}px`;
            }
        }
    });
    
    document.addEventListener('mouseup', () => {
        if (isResizing) {
            isResizing = false;
            document.body.style.cursor = '';
            resizeHandle.style.opacity = '';
            
            // 移除遮罩层
            if (overlay) {
                overlay.remove();
                overlay = null;
            }
            
            // 保存当前宽度到 localStorage
            const currentWidth = sidebar.style.width;
            if (currentWidth) {
                localStorage.setItem('datafluxSidebarWidth', currentWidth);
            }
        }
    });
}

// 关闭侧边栏
function closeSidebar(sidebar) {
    sidebar.style.width = '400px'; // 重置为默认宽度
    sidebar.classList.remove('visible');
}

// 打开侧边栏
function openSidebar(sidebar) {
    const savedWidth = localStorage.getItem('datafluxSidebarWidth');
    if (savedWidth) {
        sidebar.style.width = savedWidth;
    }
    sidebar.classList.add('visible');
}

// 切换侧边栏显示状态
function toggleSidebar() {
    const sidebar = document.querySelector('#dataflux-ai-sidebar');
    if (sidebar) {
        if (sidebar.classList.contains('visible')) {
            closeSidebar(sidebar);
        } else {
            openSidebar(sidebar);
        }
        return { success: true };
    }
    // 如果侧边栏不存在，创建它
    const newSidebar = createSidebar();
    openSidebar(newSidebar);
    return { success: true };
}

// 处理总结功能
function handleSummary() {
    console.log('开始获取页面内容...');
    
    // 内容清理函数 - 优化文本处理逻辑
    function cleanText(text) {
        return text
            // 保留段落结构,只处理多余的换行
            .replace(/\n{3,}/g, '\n\n')
            // 保留段落缩进
            .replace(/[ \t]+/g, ' ')
            // 移除零宽字符
            .replace(/[\u200B-\u200D\uFEFF]/g, '')
            // 优化中英文间的空格
            .replace(/([a-zA-Z])([\u4e00-\u9fa5])/g, '$1 $2')
            .replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, '$1 $2')
            // 移除首尾空白
            .trim();
    }

    // 判断内容有效性 - 降低阈值并增加更多判断标准
    function isValidContent(text, element) {
        const contentLength = text.replace(/\s/g, '').length;
        
        // 降低字符数阈值
        if (contentLength < 5) return false;
        
        // 检查元素可见性
        const style = window.getComputedStyle(element);
        if (style.display === 'none' || 
            style.visibility === 'hidden' || 
            style.opacity === '0') {
            return false;
        }
        
        // 检查元素位置
        const rect = element.getBoundingClientRect();
        if (rect.width === 0 || rect.height === 0) {
            return false;
        }
        
        // 检查是否在广告相关的iframe中
        if (element.closest('iframe[src*="ad"], iframe[id*="ad"]')) {
            return false;
        }
        
        return true;
    }

    // 获取主要内容 - 扩展选择器范围和优化内容收集策略
    function getMainContent() {
        // 扩展主要内容选择器
        const mainSelectors = [
            'article',
            'main',
            '[role="main"]',
            '[role="article"]',
            '.article',
            '.article-content',
            '.post-content',
            '.entry-content',
            '.main-content',
            '.content-main',
            '.page-content',
            '.blog-content',
            '.post-body',
            '#content',
            '#main',
            '.content',
            'section:not(header):not(footer)',
            '.text-content',
            '.body-content'
        ];

        // 优化排除选择器
        const excludeSelectors = [
            'script',
            'style',
            'noscript',
            'iframe:not([src*="video"]):not([src*="media"])',
            '[aria-hidden="true"]',
            '[role="complementary"]',
            '[role="banner"]',
            '[role="navigation"]',
            '[id*="sidebar"]',
            '[class*="sidebar"]',
            '[id*="menu"]',
            '[class*="menu"]',
            '[id*="nav"]',
            '[class*="nav"]:not(.navigation-content)',
            '[id*="footer"]',
            '[class*="footer"]:not(.article-footer)',
            '[id*="comment"]',
            '[class*="comment"]:not(.content-comment)',
            '[class*="share"]',
            '[class*="social"]',
            '[class*="meta"]:not(.content-meta)',
            '[class*="tag"]',
            '[class*="category"]',
            '[class*="related"]',
            '[class*="widget"]',
            '[class*="banner"]',
            '[class*="cookie"]',
            '[class*="popup"]'
        ].join(',');

        // 存储所有有效内容
        let validContents = [];
        
        // 尝试找到主要内容容器
        for (let selector of mainSelectors) {
            const elements = document.querySelectorAll(selector);
            
            for (let element of elements) {
                // 克隆元素以避免修改原始DOM
                const clonedElement = element.cloneNode(true);
                
                // 移除需要排除的元素
                const excludeElements = clonedElement.querySelectorAll(excludeSelectors);
                excludeElements.forEach(el => el.remove());
                
                const text = cleanText(clonedElement.innerText);
                if (isValidContent(text, element)) {
                    validContents.push({
                        text,
                        element,
                        weight: calculateContentWeight(element)
                    });
                }
            }
        }

        // 如果没有找到主要内容,使用改进的启发式方法
        if (validContents.length === 0) {
            // 获取所有可能包含内容的元素
            const contentElements = document.querySelectorAll('p, article, section, div > p, .content p');
            
            contentElements.forEach(element => {
                // 排除已在排除列表中的元素
                if (!element.matches(excludeSelectors)) {
                    const text = cleanText(element.innerText);
                    if (isValidContent(text, element)) {
                        validContents.push({
                            text,
                            element,
                            weight: calculateContentWeight(element)
                        });
                    }
                }
            });
        }

        // 根据权重排序并合并内容
        validContents.sort((a, b) => b.weight - a.weight);
        
        // 移除重复内容
        const uniqueContents = removeDuplicateContent(validContents);
        
        // 合并所有有效内容
        return uniqueContents.map(item => item.text).join('\n\n');
    }

    // 计算内容权重
    function calculateContentWeight(element) {
        let weight = 0;
        
        // 文本长度权重
        weight += element.innerText.length * 0.1;
        
        // 标题附近的内容权重更高
        if (element.closest('h1, h2, h3')) {
            weight += 50;
        }
        
        // 根据元素类型增加权重
        switch (element.tagName.toLowerCase()) {
            case 'article':
                weight += 100;
                break;
            case 'section':
                weight += 80;
                break;
            case 'p':
                weight += 30;
                break;
        }
        
        // 检查元素类名和ID中的关键词
        const identifiers = (element.className + ' ' + element.id).toLowerCase();
        const contentKeywords = ['content', 'article', 'post', 'entry', 'text', 'body'];
        contentKeywords.forEach(keyword => {
            if (identifiers.includes(keyword)) {
                weight += 20;
            }
        });
        
        // 根据元素在视口中的位置计算权重
        const rect = element.getBoundingClientRect();
        const viewportHeight = window.innerHeight;
        if (rect.top >= 0 && rect.bottom <= viewportHeight) {
            weight += 30;
        }
        
        return weight;
    }

    // 移除重复内容
    function removeDuplicateContent(contents) {
        const seen = new Set();
        return contents.filter(item => {
            // 使用文本的前100个字符作为指纹
            const fingerprint = item.text.slice(0, 100);
            if (seen.has(fingerprint)) {
                return false;
            }
            seen.add(fingerprint);
            return true;
        });
    }

    // 获取并处理内容
    const mainContent = getMainContent();
    
    if (mainContent) {
        console.log('提取的主要内容长度:', mainContent.length);
        
        // 增加更详细的内容分析统计
        const stats = {
            总字符数: mainContent.length,
            中文字数: (mainContent.match(/[\u4e00-\u9fa5]/g) || []).length,
            英文单词数: (mainContent.match(/[a-zA-Z]+/g) || []).length,
            段落数: mainContent.split('\n\n').length,
            句子数: (mainContent.match(/[.!?。！？]+/g) || []).length,
            数字数: (mainContent.match(/\d+/g) || []).length,
            链接数: (mainContent.match(/https?:\/\/[^\s]+/g) || []).length
        };
        
        console.log('内容统计:', stats);
        
        // 获取当前选择的模型
        // 优先使用侧边栏中的模型选择器
        let selectedModel = 'ali';
        const sidebarModelSelect = document.querySelector('#sidebar-model-select');
        if (sidebarModelSelect) {
            selectedModel = sidebarModelSelect.value;
        } else {
            // 回退到弹出框中的模型选择器
            const selectionPopup = document.querySelector('.selection-popup');
            if (selectionPopup) {
                const modelSelect = selectionPopup.querySelector('.model-select');
                if (modelSelect) {
                    selectedModel = modelSelect.value;
                }
            }
        }
        
        // 禁用UI交互元素
        setUIState(true);
        
        // 显示加载状态和准备消息区域
        const sidebarContent = document.querySelector('.dataflux-sidebar-content');
        const userMessage = createMessageElement('请帮我总结这篇文章的内容', 'user');
        sidebarContent.appendChild(userMessage);
        
        const aiMessage = createMessageElement('', 'assistant', true);
        sidebarContent.appendChild(aiMessage);
        
        sidebarContent.scrollTop = sidebarContent.scrollHeight;
        
        // 打开侧边栏显示结果
        const sidebar = document.querySelector('#dataflux-ai-sidebar');
        if (sidebar && !sidebar.classList.contains('visible')) {
            openSidebar(sidebar);
        }
        
        // 调用后端API进行总结
        fetch(`http://localhost:7878/api/v1/summary?text=${encodeURIComponent(mainContent)}&model=${selectedModel}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取总结失败');
                }
                return response.text();
            })
            .then(summaryText => {
                console.log('总结内容:', summaryText);
                
                // 更新消息元素内容
                const contentDiv = aiMessage.querySelector('.message-content');
                contentDiv.innerHTML = marked.parse(summaryText);
                
                // 处理代码块的样式
                const codeBlocks = contentDiv.querySelectorAll('pre code');
                codeBlocks.forEach(block => {
                    block.classList.add('hljs');
                    if (block.className.includes('language-')) {
                        const language = block.className.match(/language-(\w+)/)[1];
                        block.setAttribute('data-language', language);
                    }
                });
                
                // 滚动到底部
                sidebarContent.scrollTop = sidebarContent.scrollHeight;
                
                // 重新启用UI交互元素
                setUIState(false);
            })
            .catch(error => {
                console.error('总结错误:', error);
                
                // 显示错误信息
                const contentDiv = aiMessage.querySelector('.message-content');
                contentDiv.innerHTML = '总结内容时发生错误，请重试。';
                
                // 重新启用UI交互元素
                setUIState(false);
            });
    } else {
        console.log('未能提取到有效的主要内容');
        
        // 显示错误消息
        const sidebarContent = document.querySelector('.dataflux-sidebar-content');
        const userMessage = createMessageElement('请帮我总结这篇文章的内容', 'user');
        sidebarContent.appendChild(userMessage);
        
        const aiMessage = createMessageElement('无法提取页面内容，请确保当前页面有足够的文本内容。', 'assistant');
        sidebarContent.appendChild(aiMessage);
        
        sidebarContent.scrollTop = sidebarContent.scrollHeight;
        
        // 打开侧边栏显示结果
        const sidebar = document.querySelector('#dataflux-ai-sidebar');
        if (sidebar && !sidebar.classList.contains('visible')) {
            openSidebar(sidebar);
        }
    }
}

// 处理思维导图功能
function handleMindmap() {
    console.log('Mindmap function clicked');
    // TODO: 实现思维导图功能
}

// 创建消息元素
function createMessageElement(content, role, isLoading = false) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    
    const avatarDiv = document.createElement('div');
    avatarDiv.className = 'message-avatar';
    avatarDiv.innerHTML = role === 'user' ? `
        <svg viewBox="0 0 24 24">
            <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/>
        </svg>
    ` : `
        <svg viewBox="0 0 24 24">
            <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z" fill="currentColor"/>
        </svg>
    `;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    
    if (isLoading) {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'message-loading';
        loadingDiv.innerHTML = '<span></span><span></span><span></span>';
        contentDiv.appendChild(loadingDiv);
    } else {
        // 使用 marked 解析 Markdown
        if (role === 'assistant') {
            contentDiv.innerHTML = marked.parse(content);
        } else {
            contentDiv.textContent = content;
        }
    }
    
    messageDiv.appendChild(avatarDiv);
    messageDiv.appendChild(contentDiv);
    
    return messageDiv;
}

// 管理UI状态 - 添加的新函数
function setUIState(isDisabled) {
    const input = document.querySelector('#dataflux-input');
    const sendBtn = document.querySelector('#dataflux-send-btn');
    const summaryBtn = document.querySelector('#summary-btn');
    const mindmapBtn = document.querySelector('#mindmap-btn');
    
    // 设置输入区域状态
    input.disabled = isDisabled;
    input.placeholder = isDisabled ? "正在等待AI回复..." : "输入您的问题...";
    sendBtn.disabled = isDisabled || !input.value.trim();
    
    // 设置功能按钮状态
    summaryBtn.disabled = isDisabled;
    mindmapBtn.disabled = isDisabled;
    
    // 添加或移除视觉提示样式
    if (isDisabled) {
        summaryBtn.classList.add('disabled');
        mindmapBtn.classList.add('disabled');
    } else {
        summaryBtn.classList.remove('disabled');
        mindmapBtn.classList.remove('disabled');
    }
}

// 处理发送消息
function handleSendMessage(message) {
    console.log('发送消息:', message);
    
    // 禁用所有交互元素
    setUIState(true);
    
    const userMessage = createMessageElement(message, 'user');
    const sidebarContent = document.querySelector('.dataflux-sidebar-content');
    sidebarContent.appendChild(userMessage);
    
    const aiMessage = createMessageElement('', 'assistant', true);
    sidebarContent.appendChild(aiMessage);
    
    sidebarContent.scrollTop = sidebarContent.scrollHeight;

    // 获取当前选择的模型
    // 优先使用侧边栏中的模型选择器
    let selectedModel = 'ali';
    const sidebarModelSelect = document.querySelector('#sidebar-model-select');
    if (sidebarModelSelect) {
        selectedModel = sidebarModelSelect.value;
    } else {
        // 回退到弹出框中的模型选择器
        const selectionPopup = document.querySelector('.selection-popup');
        if (selectionPopup) {
            const modelSelect = selectionPopup.querySelector('.model-select');
            if (modelSelect) {
                selectedModel = modelSelect.value;
            }
        }
    }
    
    // 添加一个模型提示
    const modelNoticeElem = document.createElement('div');
    modelNoticeElem.className = 'model-notice';
    modelNoticeElem.textContent = `使用模型: ${selectedModel === 'ali' ? '阿里通义' : 'DeepSeek'}`;
    sidebarContent.appendChild(modelNoticeElem);
    sidebarContent.scrollTop = sidebarContent.scrollHeight;

    // 获取或创建会话ID
    let sessionId = localStorage.getItem('datafluxSessionId');
    const eventSource = new EventSource(`http://localhost:7878/api/v1/stream-chat?question=${encodeURIComponent(message)}${sessionId ? `&sessionId=${sessionId}` : ''}&model=${selectedModel}`);
    let responseText = '';
    let isFirstMessage = true;

    // 监听会话ID事件
    eventSource.addEventListener('SESSION', (event) => {
        console.log('新会话ID:', event.data);
        // 保存会话ID到本地存储
        localStorage.setItem('datafluxSessionId', event.data);
    });

    // 监听消息
    eventSource.onmessage = (event) => {
        try {
            if (event.data === "[DONE]") {
                eventSource.close();
                // 重新启用所有交互元素
                setUIState(false);
                return;
            }
            
            // 更新AI回复内容
            responseText += event.data;
            
            // 如果是第一条消息，移除加载动画
            if (isFirstMessage) {
                const contentDiv = aiMessage.querySelector('.message-content');
                contentDiv.innerHTML = '';
                isFirstMessage = false;
            }
            
            // 使用 marked 渲染 Markdown
            const contentDiv = aiMessage.querySelector('.message-content');
            const rendered = marked.parse(responseText);
            contentDiv.innerHTML = rendered;
            
            // 处理代码块的样式
            const codeBlocks = contentDiv.querySelectorAll('pre code');
            codeBlocks.forEach(block => {
                block.classList.add('hljs');
                if (block.className.includes('language-')) {
                    const language = block.className.match(/language-(\w+)/)[1];
                    block.setAttribute('data-language', language);
                }
            });
            
            // 滚动到底部
            sidebarContent.scrollTop = sidebarContent.scrollHeight;
        } catch (error) {
            console.error('处理消息错误:', error);
            eventSource.close();
            
            const contentDiv = aiMessage.querySelector('.message-content');
            contentDiv.innerHTML = '消息处理出错，请重试。';
            
            // 出错时也重新启用所有交互元素
            setUIState(false);
        }
    };

    // 监听错误
    eventSource.onerror = (error) => {
        console.error('SSE错误:', error);
        eventSource.close();
        
        const contentDiv = aiMessage.querySelector('.message-content');
        contentDiv.innerHTML = '连接出错，请重试。';
        
        // 出错时也重新启用所有交互元素
        setUIState(false);
    };
}

// 监听来自 background 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('Message received:', request);
    
    if (request.action === 'toggleSidebar') {
        const result = toggleSidebar();
        sendResponse(result);
    } else if (request.action === 'summary') {
        console.log('Summary action received');
        handleSummary();
        sendResponse({ success: true });
    }
    
    // 必须返回 true 以支持异步响应
    return true;
});

// 初始化
console.log('Initializing sidebar...');
createSidebar();

// 创建选中文字的弹出框
function createSelectionPopup() {
    const popup = document.createElement('div');
    popup.className = 'selection-popup';
    popup.innerHTML = `
        <div class="selection-popup-content">
            <select class="model-select" title="选择AI模型">
                <option value="deepseek">DeepSeek</option>
                <option value="ali" selected>阿里通义</option>
            </select>
            <div class="action-buttons">
                <button class="insert-mode-btn" data-mode="inline" title="切换插入模式">
                    <svg viewBox="0 0 24 24" width="14" height="14">
                        <path d="M8 5v14l11-7z" fill="currentColor"/>
                    </svg>
                </button>
                <button class="translate-btn">翻译</button>
            </div>
        </div>
    `;
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .selection-popup {
            position: absolute;
            z-index: 10000;
            background: rgba(250, 250, 252, 0.85);
            backdrop-filter: blur(12px) saturate(180%);
            -webkit-backdrop-filter: blur(12px) saturate(180%);
            border-radius: 12px;
            box-shadow: 0 2px 14px rgba(0, 0, 0, 0.08);
            border: 0.5px solid rgba(0, 0, 0, 0.08);
            overflow: hidden;
            padding: 0;
            min-width: 180px;
            max-width: 220px;
            transition: opacity 0.2s ease, transform 0.2s cubic-bezier(0.28, 0.84, 0.42, 1);
            opacity: 0;
            transform: translateY(5px) scale(0.98);
            animation: popup-appear 0.2s cubic-bezier(0.28, 0.84, 0.42, 1) forwards;
        }
        
        @keyframes popup-appear {
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        .selection-popup-content {
            display: flex;
            flex-direction: column;
            gap: 8px;
            padding: 8px;
        }
        
        .model-select {
            width: 100%;
            padding: 6px 8px;
            border-radius: 8px;
            border: 0.5px solid rgba(0, 0, 0, 0.1);
            background-color: rgba(255, 255, 255, 0.4);
            font-size: 12px;
            color: #333;
            -webkit-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath fill='%23666' d='M0 0l4 5 4-5z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 10px center;
            padding-right: 24px;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.03);
            transition: border-color 0.2s ease;
        }
        
        .model-select:focus {
            outline: none;
            border-color: rgba(107, 143, 249, 0.5);
            box-shadow: 0 0 0 2px rgba(107, 143, 249, 0.15);
        }
        
        .action-buttons {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .translate-btn {
            flex: 1;
            padding: 6px 12px;
            border-radius: 8px;
            border: none;
            background: linear-gradient(to right, #6B8FF9, #9B7BEF);
            color: white;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
            height: 28px;
            line-height: 1;
        }
        
        .translate-btn:hover {
            transform: translateY(-3px);
        }
        
        .translate-btn:active {
            transform: scale(0.97);
        }
        
        .insert-mode-btn {
            width: 28px;
            height: 28px;
            border-radius: 8px;
            border: 0.5px solid rgba(0, 0, 0, 0.08);
            background-color: rgba(255, 255, 255, 0.4);
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
            flex-shrink: 0;
        }
        
        .insert-mode-btn:hover {
            transform: translateY(-3px);
        }
        
        .insert-mode-btn:active {
            transform: scale(0.97);
        }
        
        .insert-mode-btn svg {
            transition: transform 0.3s ease;
        }
        
        /* 翻译结果容器样式 */
        .translated-text-container {
            margin-top: 5px;
            margin-bottom: 5px;
            max-width: 500px;
        }
        
        .translated-text {
            background: rgba(250, 250, 252, 0.95);
            backdrop-filter: blur(12px) saturate(180%);
            -webkit-backdrop-filter: blur(12px) saturate(180%);
            border-radius: 10px;
            border: 0.5px solid rgba(0, 0, 0, 0.08);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            animation: result-appear 0.3s cubic-bezier(0.28, 0.84, 0.42, 1) forwards;
            opacity: 0;
            transform: translateY(5px);
        }
        
        @keyframes result-appear {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .translation-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 10px;
            border-bottom: 0.5px solid rgba(0, 0, 0, 0.08);
            background-color: #f1f5ff;
        }
        
        .translation-tag {
            font-size: 12px;
            color: #4169e1;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 600;
            letter-spacing: 0.2px;
            position: relative;
            padding-left: 20px;
            height: 20px;
            line-height: 20px;
        }
        
        .translation-tag::before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 10px;
            height: 10px;
            background: linear-gradient(to right, #4169e1, #6a5acd);
            border-radius: 50%;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .translation-loading {
            display: inline-flex;
            gap: 3px;
            margin-left: 4px;
            align-items: center;
            height: 16px;
        }
        
        .translation-loading span {
            width: 3px;
            height: 3px;
            background-color: #4169e1;
            border-radius: 50%;
            animation: loading 1s infinite ease-in-out;
        }
        
        .translation-loading span:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .translation-loading span:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes loading {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-3px); }
        }
        
        .translation-delete-btn {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: none;
            background-color: transparent;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
            padding: 0;
        }
        
        .translation-delete-btn:hover {
            transform: translateY(-2px);
        }
        
        .translation-delete-btn:active {
            transform: scale(0.9);
        }
        
        .translation-delete-btn svg {
            width: 12px;
            height: 12px;
            fill: currentColor;
        }
        
        .translation-content {
            padding: 12px 14px;
            font-size: 13px;
            line-height: 1.5;
            color: #333;
        }
        
        /* 深色模式适配 */
        @media (prefers-color-scheme: dark) {
            .selection-popup {
                background: rgba(36, 36, 40, 0.85);
                border-color: rgba(255, 255, 255, 0.08);
            }
            
            .model-select {
                background-color: rgba(55, 55, 60, 0.4);
                border-color: rgba(255, 255, 255, 0.08);
                color: #eee;
                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath fill='%23aaa' d='M0 0l4 5 4-5z'/%3E%3C/svg%3E");
            }
            
            .insert-mode-btn {
                background-color: rgba(55, 55, 60, 0.4);
                border-color: rgba(255, 255, 255, 0.08);
                color: #aaa;
            }
            
            .insert-mode-btn:active {
                transform: scale(0.97);
            }
            
            .translated-text {
                background: rgba(36, 36, 40, 0.95);
                border-color: rgba(255, 255, 255, 0.08);
            }
            
            .translation-header {
                background-color: #2a2a4a;
                border-color: rgba(255, 255, 255, 0.04);
            }
            
            .translation-tag {
                color: #82a0ff;
            }
            
            .translation-tag::before {
                background: linear-gradient(to right, #82a0ff, #9f8bff);
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
            }
            
            .translation-loading span {
                background-color: #82a0ff;
            }
            
            .translation-delete-btn {
                color: #777;
            }
            
            .translation-delete-btn:active {
                transform: scale(0.9);
            }
            
            .translation-content {
                color: #eee;
            }
        }
    `;
    document.head.appendChild(style);
    document.body.appendChild(popup);
    return popup;
}

// 处理选中文字
function handleTextSelection() {
    const selection = window.getSelection();
    const selectedText = selection.toString().trim();
    
    // 移除现有的弹出框
    const existingPopup = document.querySelector('.selection-popup');
    if (existingPopup) {
        existingPopup.remove();
    }
    
    if (selectedText) {
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();
        
        const popup = createSelectionPopup();
        
        // 设置弹出框位置
        popup.style.top = `${window.scrollY + rect.bottom + 10}px`;
        popup.style.left = `${window.scrollX + rect.left}px`;
        
        // 从侧边栏获取当前选择的模型，并更新弹出框的选择器
        const sidebarModelSelect = document.querySelector('#sidebar-model-select');
        if (sidebarModelSelect) {
            const popupModelSelect = popup.querySelector('.model-select');
            if (popupModelSelect) {
                popupModelSelect.value = sidebarModelSelect.value;
            }
        }
        
        // 翻译按钮点击事件
        const translateBtn = popup.querySelector('.translate-btn');
        translateBtn.addEventListener('click', () => {
            const modelSelect = popup.querySelector('.model-select');
            const selectedModel = modelSelect.value;
            
            // 同步弹出框中的模型选择到侧边栏
            if (sidebarModelSelect) {
                sidebarModelSelect.value = selectedModel;
            }
            
            handleTranslation(selectedText, selection, selectedModel);
            popup.remove();
        });
        
        // 插入模式按钮点击事件
        const insertModeBtn = popup.querySelector('.insert-mode-btn');
        insertModeBtn.addEventListener('click', () => {
            const currentMode = insertModeBtn.dataset.mode;
            insertModeBtn.dataset.mode = currentMode === 'inline' ? 'newline' : 'inline';
            insertModeBtn.querySelector('svg').style.transform = 
                currentMode === 'inline' ? 'rotate(90deg)' : 'rotate(0deg)';
        });
    }
}

// 处理翻译
async function handleTranslation(text, selection, model) {
    const insertMode = document.querySelector('.insert-mode-btn')?.dataset.mode || 'inline';
    const range = selection.getRangeAt(0);
    
    // 创建翻译容器
    const container = document.createElement('div');
    container.className = `translated-text-container ${insertMode} loading`;

    // 设置翻译内容 - 简化的内联样式
    if (insertMode === 'inline') {
        container.innerHTML = `
            <span class="translated-text">正在翻译...</span>
            <button class="translation-delete-btn" title="关闭">
                <svg viewBox="0 0 24 24">
                    <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                </svg>
            </button>
        `;
    } else {
        container.innerHTML = `
            <div class="translated-text">
                <div class="translation-header">
                    <span class="translation-tag">
                        AI翻译
                        <div class="translation-loading">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    </span>
                    <button class="translation-delete-btn" title="关闭">
                        <svg viewBox="0 0 24 24">
                            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                        </svg>
                    </button>
                </div>
                <div class="translation-content">请耐心等待,正在进行翻译...</div>
            </div>
        `;
    }

    // 插入翻译容器
    if (insertMode === 'inline') {
        range.collapse(false);
        range.insertNode(container);
    } else {
        range.collapse(false);
        const br = document.createElement('br');
        range.insertNode(br);
        range.insertNode(container);
    }
    
    // 获取删除按钮和翻译内容元素
    const deleteBtn = container.querySelector('.translation-delete-btn');
    
    // 内联和换行模式使用不同的内容选择器
    const translationContent = insertMode === 'inline' 
        ? container.querySelector('.translated-text')
        : container.querySelector('.translation-content');
        
    // 换行模式需要获取标签
    const translationTag = insertMode === 'inline' 
        ? null
        : container.querySelector('.translation-tag');
    
    // 删除按钮事件
    deleteBtn.addEventListener('click', () => {
        // 如果是换行模式，需要同时删除换行符
        if (insertMode === 'newline') {
            // 查找并删除换行符
            const br = container.previousElementSibling;
            if (br && br.tagName === 'BR') {
                br.remove();
            } else {
                // 如果直接查找不到换行符，尝试查找父元素中的换行符
                const parent = container.parentElement;
                if (parent) {
                    const parentChildren = Array.from(parent.childNodes);
                    const containerIndex = parentChildren.indexOf(container);
                    if (containerIndex > 0) {
                        const prevNode = parentChildren[containerIndex - 1];
                        if (prevNode && prevNode.nodeType === Node.ELEMENT_NODE && prevNode.tagName === 'BR') {
                            prevNode.remove();
                        }
                    }
                }
            }
        }
        container.remove();
    });
    
    const maxRetries = 3;
    let currentTry = 0;
    
    while (currentTry < maxRetries) {
        try {
            await performTranslation(text, model, translationContent, translationTag, insertMode);
            container.classList.remove('loading');
            break;
        } catch (error) {
            currentTry++;
            console.error(`第 ${currentTry} 次翻译尝试失败:`, error);
            
            if (currentTry < maxRetries) {
                if (insertMode === 'inline') {
                    translationContent.textContent = `重试中(${currentTry}/${maxRetries})...`;
                } else {
                    translationTag.innerHTML = `翻译重试(${currentTry}/${maxRetries})
                        <div class="translation-loading">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>`;
                    translationContent.textContent = '正在重试翻译,请稍候...';
                }
                await new Promise(resolve => setTimeout(resolve, 1000 * currentTry));
            } else {
                handleTranslationError(error, translationContent, translationTag, insertMode);
            }
        }
    }
}

// 执行翻译
async function performTranslation(text, model, contentElement, tagElement, insertMode) {
    const response = await fetch(`http://localhost:7878/api/v1/translate?text=${encodeURIComponent(text)}&model=${model}`);
    console.log(response);
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const translatedText = await response.text();
    
    if (insertMode === 'inline') {
        // 设置title属性，以便用户可以在悬停时查看完整文本
        contentElement.textContent = translatedText;
        contentElement.title = translatedText;
        
        // 检查文本是否超出可见区域
        setTimeout(() => {
            const containerWidth = getMaxWidthByScreenSize();
            const textWidth = getTextWidth(translatedText, window.getComputedStyle(contentElement).font);
            
            // 如果文本宽度超过最大宽度，添加省略号和工具提示
            if (textWidth > containerWidth) {
                contentElement.setAttribute('data-tooltip', translatedText);
                contentElement.parentElement.classList.add('tooltip-enabled');
            }
        }, 10); // 短暂延迟以确保DOM已更新
    } else {
        tagElement.textContent = 'AI翻译';
        contentElement.textContent = translatedText;
    }
}

// 根据屏幕尺寸获取最大宽度
function getMaxWidthByScreenSize() {
    const screenWidth = window.innerWidth;
    if (screenWidth <= 768) {
        return 150;
    } else if (screenWidth <= 1024) {
        return 250;
    } else {
        return 350;
    }
}

// 获取文本的实际像素宽度
function getTextWidth(text, font) {
    const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    const context = canvas.getContext("2d");
    context.font = font;
    const metrics = context.measureText(text);
    return metrics.width;
}

// 处理翻译错误
function handleTranslationError(error, contentElement, tagElement, insertMode) {
    if (insertMode === 'inline') {
        contentElement.textContent = '翻译失败';
        contentElement.parentElement.classList.add('error');
    } else {
        tagElement.textContent = '翻译失败';
        tagElement.style.color = '#ff4d4f';
        tagElement.style.fontWeight = '600';
        
        // 同时修改小圆点颜色
        const tagParent = tagElement.parentElement;
        if (tagParent) {
            const style = document.createElement('style');
            style.textContent = `
                .translation-tag.error::before {
                    background: linear-gradient(to right, #ff4d4f, #ff7875) !important;
                }
            `;
            document.head.appendChild(style);
            tagElement.classList.add('error');
        }
        
        if (error.message.includes('HTTP error')) {
            contentElement.textContent = '服务器错误，请稍后重试。';
        } else if (error.message.includes('Failed to fetch')) {
            contentElement.textContent = '无法连接到翻译服务，请检查服务是否启动。';
        } else {
            contentElement.textContent = '翻译服务出现错误，请重试。';
        }
    }
}

// 添加选中文字事件监听
document.addEventListener('mouseup', (e) => {
    // 如果点击的是弹出框内的元素，不处理
    if (e.target.closest('.selection-popup')) {
        return;
    }
    handleTextSelection();
});

// 点击页面其他地方时隐藏弹出框
document.addEventListener('mousedown', (e) => {
    if (!e.target.closest('.selection-popup')) {
        const popup = document.querySelector('.selection-popup');
        if (popup) {
            popup.remove();
        }
    }
});